package bookshare;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

/**
 *
 * @author Kathi
 */
@WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {

    /**
     * Processes requests for both HTTP
     * <code>GET</code> and
     * <code>POST</code> methods.
     *
     * @param request servlet request
     * @param response servlet response
     * @throws ServletException if a servlet-specific error occurs
     * @throws IOException if an I/O error occurs
     */
    
    public LoginServlet() {
        super();
    }
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        HttpSession session = request.getSession(true);
        PrintWriter out = response.getWriter();
        response.setContentType("text/html");
        
        // Session killen bei Logout und zurück auf die Startseite
        if(request.getParameter("action").equals("logout")) {
            session.invalidate();
            response.sendRedirect("index.jsp");
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        
        HttpSession session = request.getSession(true);
                
        // if this is a new session set login to false
	if(session.getAttribute("loginCorrect") == null)
		session.setAttribute("loginCorrect", false); // set login variable
        
        // get login parameters
	String matrikelnummer = request.getParameter("matrikelnummer");  
	String passwort = request.getParameter("passwort");
        
        // check login parameters
        SQLabfrage abfrage = new SQLabfrage();
	if(!matrikelnummer.equals("") && !passwort.equals("")){
            try {
                int id = abfrage.proveData(matrikelnummer, passwort);
                if(id != 0){
                    //overwrite login variable
                    session.setAttribute("loginCorrect", true);
                    session.setAttribute("userID", id);
                    // return to index page
                    response.sendRedirect("index.jsp");
                }
                else {
                    response.sendRedirect("index.jsp?error=2");
                }
            } catch (Exception e) {
                System.out.println("Ooops");
            }
	}
        else {
            response.sendRedirect("index.jsp?error=3");
        }
    }
}